/*
 * @(#)CamCacheLoaderListener.java
 * 
 * Create Version: 1.0.0
 * Author: James Liu
 * Create Date: 2009-12-09
 * 
 * Copyright (c) 2009 ASPire Information Technologies Ltd. All Right Reserved.
 */


package com.aspire.boc.mms.wmf.cam;


import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * 这个类是实现ServletContextListener接口的，
 * 用于在WebApp启动和关闭时做预处理和后处理。
 *
 * @version 1.0.0   2009-12-09
 * @author  James Liu
 */
public class CamCacheLoaderListener implements ServletContextListener {
    
    /* CAM缓存默认超时时间，默认为3600秒，即1小时。 */
    private static long DEFAULT_CAM_CACHE_TIMEOUT = 3600 * 1000;
    private static Log log = LogFactory.getLog(CamCacheLoaderListener.class);
    
    private Timer timer = new Timer();
    
    
    public void contextInitialized(ServletContextEvent sce) {
        
        log.info("CamCacheLoaderListener.contextInitialized(): START");
        
        // 装载参数
        long timeout = DEFAULT_CAM_CACHE_TIMEOUT;
        String camCacheTimeout = sce.getServletContext().getInitParameter("camCacheTimeout");
        if (camCacheTimeout != null) {
            try {
                timeout = Long.parseLong(camCacheTimeout) * 1000;
            } catch (NumberFormatException e) {}
        }
        
        // 装载CamCache
        CamCache camCache = CamCache.getInstance();
        
        // 获得CamCache的刷新时间，设置cacheTimer。30分钟
        CamCacheLoaderTimerTask timerTask = new CamCacheLoaderTimerTask(camCache);
        this.timer.schedule(timerTask, 0, timeout);
        
        log.info("CamCacheLoaderListener.contextInitialized(): START FINISHED");
    }
    
    public void contextDestroyed(ServletContextEvent sce) {
        log.info("CamCacheLoaderListener.contextDestroyed(): Destroy");
        this.timer.cancel();
        log.info("CamCacheLoaderListener.contextDestroyed(): Destroy FINISHED");
    }
}